package com.frxuexi.apps

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import androidx.lifecycle.lifecycleScope
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.apps.databinding.ActivityNetAppBinding
import com.frxuexi.apps.entity.Apps
import com.frxuexi.apps.intent.AppIntent
import com.frxuexi.apps.viewmodel.NetViewModel
import com.frxuexi.lib_http.download.DownloadState
import kotlinx.coroutines.launch


@Route(path = "/apps/NetAppActivity")
class NetAppActivity : AppCompatActivity() {
    lateinit var vm:NetViewModel
    lateinit var db:ActivityNetAppBinding
    lateinit var path:String
    val apkPath by lazy {
        getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db= ActivityNetAppBinding.inflate(layoutInflater)
        setContentView(db.root)
        vm=ViewModelProvider(this).get(NetViewModel::class.java)



        lifecycleScope.launch {
            vm.netState.collect{
                when(it){
                    is AppState.onSuccess->{
                        Log.i("===",it.data.toString())
                        db.netCom.setContent {
                            NetAppPage(it.data, onClick = {
                                finish()
                            }){downloadApk(apps = it)
                            }
                        }
                    }
                    is AppState.onError->{
                        Log.i("===",it.msg)
                    }
                    else->{}
                }
            }
        }

        lifecycleScope.launch {
            vm.downState.collect{
                when(it){
                    is DownloadState.onSuccess->{
                        ToastUtils.showLong("下载成功")
                        Log.i("===","下载成功")
                        /*db.netCom.setContent {
                            NetAppPage(it.data, onClick = {
                                finish()
                            }){downloadApk(apps = it)
                            }
                        }*/
                    }
                    is DownloadState.onError->{
                        Log.i("===",it.msg)
                    }
                    else->{}
                }
            }
        }

        lifecycleScope.launch {
            vm.netChannel.send(AppIntent.selClientApp)
        }

    }


    fun downloadApk(apps: Apps){
        lifecycleScope.launch {
            vm.netChannel.send(AppIntent.downloadApk(apps,apkPath+"/"+apps.appName+".apk"))
//            vm.downloadApk(apk = apps,apkPath+apps.appName+".apk")
        }
    }
}